package com.cman777.springc.common.helper;

/**
 * @author chenzhicong
 * @time 2020/4/14 17:51
 * @description
 */

import com.google.common.base.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Auther:
 * @Date: 2018/10/19 15:49
 * @Description:
 */
public class AESUtil {
    static Logger logger = LoggerFactory.getLogger(AESUtil.class);
    private static String charset = "utf-8";
    // 偏移量
    private static int offset = 16;
    // 加密器类型:加密算法为AES,加密模式为CBC,补码方式为PKCS5Padding
    private static String transformation = "AES/CBC/PKCS5Padding";
    // 算法类型：用于指定生成AES的密钥
    private static String algorithm = "AES";


    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key     加密密码
     * @return
     */
    public static String encrypt(String content, String key) {
        try {

            byte[] keyBytes = key.getBytes(Charsets.UTF_8);
            //构造密钥
            SecretKeySpec skey = new SecretKeySpec(keyBytes, algorithm);
            //创建初始向量iv用于指定密钥偏移量(可自行指定但必须为128位)，因为AES是分组加密，下一组的iv就用上一组加密的密文来充当
            IvParameterSpec iv = new IvParameterSpec(keyBytes, 0, offset);
            //创建AES加密器
            Cipher cipher = Cipher.getInstance(transformation);
            byte[] byteContent = content.getBytes(Charsets.UTF_8);
            //使用加密器的加密模式
            cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //使用BASE64对加密后的二进制数组进行编码
            return Base64Utils.byteArrayToBase64(result);
        } catch (Exception e) {
            logger.info("", e);
        }
        return null;
    }

    /**
     * AES解密
     *
     * @param content 待解密内容
     * @param key     解密密钥
     * @return 解密之后
     * @throws Exception
     */
    public static String decrypt(String content, String key) {
        try {
            byte[] keyBytes = key.getBytes(Charsets.UTF_8);
            SecretKeySpec skey = new SecretKeySpec(keyBytes, algorithm);
            IvParameterSpec iv = new IvParameterSpec(keyBytes, 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            //解密时使用解密模式
            cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(Base64Utils.base64ToByteArray(content));
            return new String(result); // 解密
        } catch (Exception e) {
            logger.info("", e);
        }
        return null;
    }


    public static String generateAesKey(int bit) {
        try {
            //实例化
            KeyGenerator kgen = null;
            kgen = KeyGenerator.getInstance("AES");
            //设置密钥长度
            kgen.init(bit);
            //生成密钥
            SecretKey skey = kgen.generateKey();
            //返回密钥的base64编码
            return Base64Utils.byteArrayToBase64(skey.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
  /*public static void main(String[] args){


  System.out.println(encrypt("{\n" + "  \"test\": \"string\"\n" + "}", "mytfYaaDBaFasZEJ"));
  System.out.println(decrypt("AlWRDcdK8SzZ7qtuSiO009Ly/XexEf3ieDQWQ6LfFKk=","mytfYaaDBaFasZEJ"));
  }*/
  public static void main(String[] args) {
    //System.out.println(decrypt("J/9uyWBr+/kCtWlV18iPIg==","Q9qc7GFMOXgc9FtW"));
   /* System.out.println(encrypt("{\n" +
            "  \"begRow\": 0,\n" +
            "  \"isPage\": true,\n" +
            "  \"pageNo\": 0,\n" +
            "  \"pageSize\": 10,\n" +
            "  \"queryParams\": {\n" +
            "   \"provinceCode\":500000,\n" +
            "   \"cityCode\":500100,\n" +
            "   \"lngX\":106.58314360,\n" +
            "   \"latY\":29.55918370,\n" +
            "   \"groupCode\":\"B511\"\n" +
            "  }\n" +
            "}","EH168OiL9lsnvn7w"));*/

    System.out.println(decrypt("hew0zs/ehhKgghMb+AB7jIb2ZvSJHZOq2izvuz175RbR6sym3/QUuVKRTHPb32lVeXsTPGyngxFD1thUL5jZybCQlb1DHoj3WZhV++wxy0U0jOKIOu9b1Ou/wn5kgdSNR8/cQEl0tdMJlAfdwTTnqvcoCw7LxBqa/S4bARzCn/jbg7rbrQ3InyBotmOnKsoDEBXc6kQiFlNZbulOLjTLgUz7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